package com.hundsun.cprs.yyt.util;

import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 网络相关通用方法，如取得IP等
 * 
 * @author linbo
 * @version $Id: NetworkUtil.java,v 1.1.1.1.RC1 2017年8月23日 Exp $
 */
public class NetworkUtil {
	private static final Log logger = LogFactory.getLog(NetworkUtil.class);

	/**
	 * 获取可修改的http请求参数列表
	 * 
	 * @param request
	 * @return map<String, String>
	 */

	public static Map<String, String> getRequestParameters(HttpServletRequest request) {
		Map<String, String> paraMap = new HashMap<String, String>();
		Map requestParams = request.getParameterMap();

		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
			}
			// 商品描述和商品标题中可能含有中文，与接口中定义，如果是中文，都用UTF-8
			if (StringUtils.equals(name, "title") || StringUtils.equals(name, "invoice_header")) {
				try {
					if (request.getMethod().equals("GET")) {
						valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
					}
					valueStr = URLDecoder.decode(valueStr, "UTF-8");
				} catch (Exception e) {
					logger.error("this server can't support 8859_1 and utf-8 encoding");
				}
			}

			paraMap.put(name, valueStr);
		}
		return paraMap;
	}

	/**
	 * 获取http get方式经编码后的请求串
	 * 
	 * @param queryMap
	 * @param encoding
	 * @return string
	 * @throws UnsupportedEncodingException
	 */
	public static String getEncodedQueryString(Map<String, String> queryMap, String encoding)
			throws UnsupportedEncodingException {
		StringBuffer sb = new StringBuffer();
		if (null != queryMap && 0 != queryMap.size() && StringUtils.isNotBlank(encoding)) {
			for (String key : queryMap.keySet()) {
				String val = queryMap.get(key);
				if (StringUtils.isNotBlank(key) && StringUtils.isNotBlank(val)) {
					sb.append(sb.length() > 0 ? "&" : "");
					key = URLEncoder.encode(key, encoding);
					val = URLEncoder.encode(val, encoding);
					sb.append(key + "=" + val);
				}
			}
		}
		return sb.length() > 0 ? sb.toString() : null;
	}

	public static URL getEncodedUrl(String queryUrl, Map<String, String> queryMap, String encoding) {
		try {
			String queryString = getEncodedQueryString(queryMap, encoding);
			int queryIndex = queryUrl.indexOf("?");
			if (-1 != queryIndex) {
				if (StringUtils.isBlank(queryString)) {
					queryUrl = queryUrl.substring(0, queryIndex);
				} else {
					queryUrl = queryUrl + queryString;
				}
			} else {
				if (StringUtils.isNotBlank(queryString)) {
					queryUrl = queryUrl + "?" + queryString;
				}
			}
			return new URL(queryUrl);
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 判断网络是否可用,等同于访问网络
	 * 
	 * @param url
	 * @return true or false
	 */
	public static boolean isCanConnection(String url) {
		try {
			URL urlInfo = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) urlInfo.openConnection();
			int state = conn.getResponseCode();
			if (state == 200) {
				return true;
			}
		} catch (Exception e) {
			logger.error("the url:" + url + " is can't connection", e);
		}
		return false;
	}

	/**
	 * 此方法在转发请求的HTTP头信息中，增加了 X-FORWARDED-FOR 信息用以跟踪原有的客户端IP地址和原来客户端请求的服务器地址
	 * 
	 * @param request
	 * @return String
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("X-Forwarded-For");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	/**
	 * 获取服务器IP
	 * 
	 * @author linbo
	 * @return
	 */
	public static String getServerIp() {
		String hostAddress;
		try {
			InetAddress localhost = InetAddress.getLocalHost();
			hostAddress = localhost.getHostAddress();
		} catch (UnknownHostException e) {
			hostAddress = "127.0.0.1";
		}
		return hostAddress;
	}
}
